// Fetch SSE 请求工具
export const fetchSSE = async (
  url,
  data,
  { headers = [], onMessage, onError, onClosed, onFinished }
) => {
  let reader, decoder;
  if (!url) {
    throw new Error("url 不能为空");
  }
  const response = await fetch(url, {
    method: "POST",
    body: data ? JSON.stringify(data) : null,
    headers: {
      ...headers,
    },
  });

  if (!response.ok) {
    const error = new Error('请求异常');
    onFinished && onFinished({ success: false, type: 'finished', error });
    onError && onError({ success: false, type: 'error', error });
    return;
  }

  reader = response.body.getReader();
  decoder = new TextDecoder();

  const readLoop = async () => {
    while (true) {
      const { done, value } = await reader.read();
      if (done) {
        break;
      }
      const chunk = decoder.decode(value);
      const lines = chunk.split("\n");
      for (const line of lines) {
        if (line.trim() && line.trim()?.startsWith('data:{')) {
          try {
            const data = JSON.parse(line.substring(5, line.length));
            if(data?.output?.finish_reason === "stop"){
              onFinished && onFinished({ success: true, type: 'finished', data });
            }
            onMessage && onMessage({ success: true, type: 'message', data });
          } catch (error) {
            debugger
            onFinished && onFinished({ success: false, type: 'finished', error });
            onError && onError({ success: false, type: 'error', error });
          }
        }
      }
    }
  };

  readLoop().catch((error) => {
    onFinished && onFinished({ success: false, type: 'finished', error });
    onError && onError({ success: false, type: 'error', error });
  });

  // 返回一个函数，用于关闭SSE连接
  return () => {
    reader.cancel();
    onFinished && onFinished({ success: false, type: 'finished' });
    onClosed && onClosed({ success: false, type: 'closed' });
  };
};
